package com.zkc.zbar;

import java.io.IOException;
import java.util.List;

import com.zkc.i2ctools.i2c;
import com.zkc.io.LightEmGpio;
import com.zkc.view.VerticalSeekBar;
import com.zkc.zbarscan.R;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class CaptureActivity extends Activity implements SensorEventListener {

	private static final float BEEP_VOLUME = 0.10f;
	private static final long VIBRATE_DURATION = 200L;
	private boolean hasSurface;
	public static Camera mCamera;
	private CameraPreview mPreview;
	private Handler autoFocusHandler;
	private MediaPlayer mediaPlayer;
	private boolean playBeep = true;
	ImageScanner scanner;
	private boolean previewing = true;
	public static boolean isScanOpen = false;
	public static LightEmGpio gpio;
	private static i2c i2c;
	private static final String i2cDev[] = { "i2c-0", "i2c-1", "i2c-2", "i2c-3" };
	private static final String TAG = null;
	private static int i2cHander;
	private EditText et_setregnum;// 写入寄存器
	private VerticalSeekBar verticalSeekBar;// 拉动数据
	private TextView tv_datanum;// 显示拉动值
	private ImageView zdimg, sdimg;
	boolean iszdsetting = true;// 是否手动设置
	boolean isOpenWhite = true;
	boolean isopenGreen = false;
	boolean isStartScan = false;
	SensorManager sensorManager = null;// 传感器管理器引用
	Sensor lightSensor = null;// 光线传感器引用
	boolean ismanual = false;
	private String gao = "00";
	private String di = "80";
	private int gaonum = 0;
	private int dinum = 10;
	private int bgnum = 0;

	int isopenThatLight = 2;// 0开白灯，1开红灯 ， 2 不开灯
	int time = 0;
	FrameLayout preview;
	private Switch mSwitch;
	private String codeMessage = null;

	static {
		System.loadLibrary("iconv");
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		// 全屏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.zbar_capture);

		findById();
		gpio = new LightEmGpio();
		i2c = new i2c();
		// 获得传感器管理器实例
		sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		// 获得光线传感器实例
		lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
		verticalSeekBar
				.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onProgressChanged(SeekBar seekBar,
							int progress, boolean fromUser) {
						// TODO Auto-generated method stub
						if (!ismanual) {
							new Thread(sdrun).start();
						}
						String regString = et_setregnum.getText().toString()
								.trim();
						if (regString.length() <= 0) {
							Toast.makeText(CaptureActivity.this, "请输入寄存器", 3000)
									.show();
							verticalSeekBar.setProgress(0);
							tv_datanum.setText("0");
						} else {
							tv_datanum.setText(progress + "");
							String num = Integer.toHexString(progress);

							String num16 = "";

							if (num.length() == 1) {
								num16 = "0" + num;
							} else {
								num16 = num;
							}
							int[] bufWriteReg;
							int[] bufWriteData;

							bufWriteReg = hexStringToBytes(et_setregnum
									.getText().toString().trim());
							bufWriteData = hexStringToBytes(num16);
							commandPublic(bufWriteReg, bufWriteData);
						}
					}
				});
		zdimg.setOnClickListener(new ImgClick());
		sdimg.setOnClickListener(new ImgClick());
		hasSurface = false;
		// 自动模式开关
		mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					// 开启自动
					iszdsetting = false;

					new Thread(zdrun).start();
				} else {
					// 关闭自动，手动参数设置

					ismanual = false;
					iszdsetting = true;
					photosensitive(80, 0, 35);
				}
			}
		});
		mSwitch.setChecked(false);

	}

	/**
	 * 初始化控件
	 */
	public void findById() {
		zdimg = (ImageView) findViewById(R.id.zdImg);
		sdimg = (ImageView) findViewById(R.id.sdImg);
		preview = (FrameLayout) findViewById(R.id.cameraPreview);
		et_setregnum = (EditText) findViewById(R.id.et_setregnum);
		verticalSeekBar = (VerticalSeekBar) findViewById(R.id.verticalSeekBar);
		tv_datanum = (TextView) findViewById(R.id.tv_setdatanum);
		mSwitch = (Switch) findViewById(R.id.mSwitch);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isStartScan = true;
		// this.isScanOpen = true;
		try {

			// 为传感器管理器注册监听
			sensorManager.registerListener(this, lightSensor,
					SensorManager.SENSOR_DELAY_NORMAL);
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

			autoFocusHandler = new Handler();

			/* Instance barcode scanner */
			scanner = new ImageScanner();
			scanner.setConfig(0, Config.X_DENSITY, 3);
			scanner.setConfig(0, Config.Y_DENSITY, 3);
			preview.removeAllViews();

			mCamera = getCameraInstance();

			mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);

			preview.addView(mPreview);

			mCamera.setPreviewCallback(previewCb);

			mCamera.startPreview();
			previewing = true;
			mCamera.autoFocus(autoFocusCB);

			// 初始化声音
			AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);

			// 初始化声音
			initBeepSound();
			// 默认手动设置参数
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					ismanual = false;
					iszdsetting = true;
					photosensitive(50, 0, 35);
				}
			}).start();
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}

	}

	/**
	 * 10秒关闭白灯线程
	 * 
	 * @author zkc-soft2
	 * 
	 */
	class TimeThread extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();

			time = 0;

			while (time++ < 10000) {
				if (codeMessage != null) {

					break;
				} else if (time == 9999) {
					// 关闭白灯
					try {
						if (isOpenWhite == false) {
							Thread.sleep(10);
							gpio.closeWhiteLight();
							Thread.sleep(20);
							gpio.openWhiteLight();
							Thread.sleep(100);
							gpio.closeWhiteLight();
							isOpenWhite = true;
						}
						isExposure = false;
					} catch (Exception e) {
						// TODO: handle exception
					}
					break;
				}
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

	class ImgClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.zdImg:
				// 手动参数设置
				ismanual = false;
				iszdsetting = true;// 允许设置
				mSwitch.setChecked(false);
				photosensitive(50, 0, 35);
				break;
			case R.id.sdImg:
				// 手动参数调节
				iszdsetting = false;// 不进行设置
				new Thread(sdrun).start();
				showManualWindow(v);
				break;
			}
		}

	}

	// 设置手动模式
	Runnable sdrun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub

			int[] bufWriteReg;
			int[] bufWriteData;
			ismanual = true;

			try {

				bufWriteReg = hexStringToBytes("fe");
				bufWriteData = hexStringToBytes("00");
				commandPublic(bufWriteReg, bufWriteData);
				Thread.sleep(50);
				bufWriteReg = hexStringToBytes("b6");
				bufWriteData = hexStringToBytes("01");
				commandPublic(bufWriteReg, bufWriteData);
				Thread.sleep(50);
				bufWriteReg = hexStringToBytes("fe");
				bufWriteData = hexStringToBytes("00");
				commandPublic(bufWriteReg, bufWriteData);
				Thread.sleep(50);
				bufWriteReg = hexStringToBytes("82");
				bufWriteData = hexStringToBytes("fc");
				commandPublic(bufWriteReg, bufWriteData);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	};
	// 自动模式
	Runnable zdrun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub

			int[] bufWriteReg;
			int[] bufWriteData;
			ismanual = false;

			try {
				bufWriteReg = hexStringToBytes("86");
				bufWriteData = hexStringToBytes("00");
				commandPublic(bufWriteReg, bufWriteData);
				Thread.sleep(50);
				bufWriteReg = hexStringToBytes("fe");
				bufWriteData = hexStringToBytes("00");
				commandPublic(bufWriteReg, bufWriteData);
				Thread.sleep(50);
				bufWriteReg = hexStringToBytes("b6");
				bufWriteData = hexStringToBytes("03");
				commandPublic(bufWriteReg, bufWriteData);
				Thread.sleep(50);
				bufWriteReg = hexStringToBytes("fe");
				bufWriteData = hexStringToBytes("00");
				commandPublic(bufWriteReg, bufWriteData);
				Thread.sleep(50);
				bufWriteReg = hexStringToBytes("82");
				bufWriteData = hexStringToBytes("fe");
				commandPublic(bufWriteReg, bufWriteData);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}

			handler2.sendMessage(new Message());

		}
	};
	Handler handler2 = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			Toast.makeText(getApplicationContext(), "设置成功", 2000).show();
		}

	};

	/**
	 * 爆光浮动通知显示窗口
	 * 
	 * @param parent
	 *            浮动位置
	 * @param content
	 */
	private void showManualWindow(View parent) {
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = layoutInflater.inflate(R.layout.solarize, null);
		SeekBar diBar = (SeekBar) view.findViewById(R.id.di_seekBar);
		SeekBar gaoBar = (SeekBar) view.findViewById(R.id.gao_seekBar);
		SeekBar baoguangBar = (SeekBar) view.findViewById(R.id.bgdseekBar);
		diBar.setProgress(dinum);
		gaoBar.setProgress(gaonum);
		baoguangBar.setProgress(bgnum);
		final TextView bgdText = (TextView) view.findViewById(R.id.bgdtext);
		final TextView ditext = (TextView) view.findViewById(R.id.ditext);
		final TextView gaotext = (TextView) view.findViewById(R.id.gaotext);
		ditext.setText(dinum + "");
		gaotext.setText(gaonum + "");
		bgdText.setText(bgnum + "");
		diBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				int progress = seekBar.getProgress();
				di = Integer.toHexString(progress);
				if (di.length() == 1) {
					di = "0" + di;
				}
				dinum = progress;
				ditext.setText(progress + "");
				settingGaoDi(gao, di);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub

			}
		});
		gaoBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				int progress = seekBar.getProgress();
				gao = Integer.toHexString(progress);
				if (gao.length() == 1) {
					gao = "0" + gao;
				}
				gaonum = progress;
				gaotext.setText(progress + "");
				settingGaoDi(gao, di);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub

			}
		});
		baoguangBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				bgdText.setText(progress + "");
				bgnum = progress;
				baoguang(Integer.toHexString(progress));
			}
		});
		// 创建一个PopuWidow对象
		PopupWindow popupWindow = new PopupWindow(view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		// 使其聚集
		popupWindow.setFocusable(true);
		// 设置允许在外点击消失
		popupWindow.setOutsideTouchable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		// 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
		int xPos = windowManager.getDefaultDisplay().getWidth() / 2
				- popupWindow.getWidth() / 2;

		int[] location = new int[2];
		parent.getLocationOnScreen(location);
		view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		Rect anchorRect = new Rect(location[0], location[1], location[0]
				+ parent.getWidth(), location[1] + parent.getHeight());

		view.setBackgroundResource(R.drawable.mini_year_month_picker_down);
		popupWindow.showAsDropDown(parent);

	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == 135 || keyCode == 136 || keyCode == 66) {
			if (isopenGreen) {
				// 关绿灯
				gpio.closelight();
				if (isopenThatLight == 0) {
					// 是否允许打开白灯
					if (isOpenWhite) {
						try {
							// 开白灯
							gpio.closeWhiteLight();
							Thread.sleep(50);
							gpio.openWhiteLight();
							Thread.sleep(100);
							gpio.closeWhiteLight();
							Thread.sleep(20);
							codeMessage = null;
							isOpenWhite = false;

							if (time > 0) {
								// 关闭时间监听线程
								time = 10000;
							}
							// 启动时间监听，在10秒内无扫描到条码信息至关闭白灯
							TimeThread timeThread = new TimeThread();
							timeThread.start();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					isStartScan = true;// 允许进行扫描
					// 进行自动曝光
					if (iszdsetting) {
						isExposure = false;
						ExposureThread exposureThread = new ExposureThread();
						exposureThread.start();
					}

				}

				return true;
			}
		}
		return super.onKeyUp(keyCode, event);
	}

	boolean isExposure = true;

	/**
	 * 曝光自动调节
	 * 
	 * @author zkc-soft2
	 * 
	 */
	class ExposureThread extends Thread {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			int bg = 0;
			isExposure = true;
			ismanual = false;
			iszdsetting = true;// 允许设置
			while (isExposure) {
				try {
					if (bg == 0) {
						gao = "00";
						di = "05";
						settingGaoDi(gao, di);
						sleep(50);
						baoguang(Integer.toHexString(bg));
					} else {
						photosensitive(35, 0, bg);

					}
					if (bg == 60) {
						bg = 0;
					} else {
						bg += 20;
					}

					sleep(200);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

	/**
	 * 关白灯
	 */
	public void closeWhite() {
		try {
			// 关闭白灯
			if (isOpenWhite == false) {
				Thread.sleep(10);
				gpio.closeWhiteLight();
				Thread.sleep(50);
				gpio.openWhiteLight();
				Thread.sleep(100);
				gpio.closeWhiteLight();
				isOpenWhite = true;
				Thread.sleep(10);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		isExposure = false;
	}

	/**
	 * 开绿灯
	 */
	public void openGreen(KeyEvent event) {
		if (event.getRepeatCount() == 0) {
			// 开绿灯
			gpio.openGreenLight();
			isopenGreen = true;
			isStartScan = false;

		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case 66:
			try {
				closeWhite();// 当白灯亮则关白灯
				openGreen(event);// 开绿灯
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case 135:

			try {
				closeWhite();// 当白灯亮则关白灯
				openGreen(event);// 开绿灯
				return true;
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			break;
		case 136:

			try {
				closeWhite();// 当白灯亮则关白灯
				openGreen(event);// 开绿灯
				return true;
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void onPause() {
		super.onPause();
		releaseCamera();
		// 注销
		sensorManager.unregisterListener(this, lightSensor);
	}

	@Override
	protected void onDestroy() {
		// this.isScanOpen = false;
		// 关灯
		gpio.closelight();
		closeWhite();
		super.onDestroy();
	}

	/** A safe way to get an instance of the Camera object. */
	public static Camera getCameraInstance() {
		Camera c = null;
		try {
			c = Camera.open(CameraInfo.CAMERA_FACING_FRONT);
		} catch (Exception e) {
			c = Camera.open(CameraInfo.CAMERA_FACING_BACK);
		}
		return c;
	}

	private void releaseCamera() {
		if (mCamera != null) {
			isStartScan = false;
			hasSurface = false;
			previewing = false;
		}
	}

	// 自动对焦
	private Runnable doAutoFocus = new Runnable() {
		public void run() {
			if (previewing)
				mCamera.autoFocus(autoFocusCB);
		}
	};

	PreviewCallback previewCb = new PreviewCallback() {
		public void onPreviewFrame(byte[] data, Camera camera) {
			Camera.Parameters parameters = camera.getParameters();
			Size size = parameters.getPreviewSize();
			if (isStartScan) {

				Image barcode = new Image(size.width, size.height, "Y800");
				barcode.setData(data);

				int result = scanner.scanImage(barcode);

				if (result != 0) {

					previewing = false;
					// 获取扫描数据
					SymbolSet syms = scanner.getResults();

					isStartScan = false;
					playBeepSoundAndVibrate();// 播放声音和振动代表成功获取二维码

					for (Symbol sym : syms) {
						codeMessage = sym.getData();
						if (getIntent().getData() != null) {
							Intent intent = getIntent();
							intent.putExtra("code", sym.getData());
							setResult(201, intent);
							finish();
						} else {
							Toast.makeText(getApplicationContext(),
									sym.getData(), 1000).show();
						}
					}

					closeWhite();// 关闭白灯
				}
			}
		}
	};

	/**
	 * 自动对焦回调
	 */
	AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
		public void onAutoFocus(boolean success, Camera camera) {
			autoFocusHandler.postDelayed(doAutoFocus, 1000);
		}
	};

	/**
	 * 初始化声音
	 */
	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);
			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	/**
	 * 播放声音
	 */
	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
	}

	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	/**
	 * 指令发送
	 * 
	 * @param bufWriteReg
	 * @param bufWriteData
	 */
	public void commandPublic(int[] bufWriteReg, int[] bufWriteData) {
		int[] bufSlaveAddr = hexStringToBytes("3c");
		int[] bufData = new int[bufWriteData.length + bufWriteReg.length];
		for (int j = 0; j < bufWriteReg.length; j++) {
			bufData[j] = bufWriteReg[j];
		}

		System.arraycopy(bufWriteData, 0, bufData, bufWriteReg.length,
				bufWriteData.length);
		i2cHander = i2c.open("/dev/" + i2cDev[0]);
		i2c.write(i2cHander, bufSlaveAddr[0], bufWriteReg[0], bufData,
				bufData.length);
		i2c.close(i2cHander);
	}

	// 调节快门爆光
	public void photosensitive(final int setdi, final int setgao,
			final int setbg) {

		if (iszdsetting) {

			try {
				if (ismanual == false) {

					int[] bufWriteReg;
					int[] bufWriteData;

					bufWriteReg = hexStringToBytes("fe");
					bufWriteData = hexStringToBytes("00");
					commandPublic(bufWriteReg, bufWriteData);
					Thread.sleep(20);
					bufWriteReg = hexStringToBytes("b6");
					bufWriteData = hexStringToBytes("01");
					commandPublic(bufWriteReg, bufWriteData);
					Thread.sleep(20);
					bufWriteReg = hexStringToBytes("fe");
					bufWriteData = hexStringToBytes("00");
					commandPublic(bufWriteReg, bufWriteData);
					Thread.sleep(20);
					bufWriteReg = hexStringToBytes("82");
					bufWriteData = hexStringToBytes("fc");
					commandPublic(bufWriteReg, bufWriteData);
					Thread.sleep(20);
				}

				di = setdi + "".toString().trim();
				dinum = setdi;
				gao = "0".toString().trim() + setgao;
				gaonum = setgao;
				bgnum = setbg;
				final int bg = setbg;
				// ismanual=true;

				settingGaoDi(gao, di);
				// 高低
				Thread.sleep(100);
				// 曝光
				baoguang(Integer.toHexString(bg));

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
		}

	}

	/**
	 * 调节高低
	 */
	public void settingGaoDi(String setGao, String setDi) {

		int[] bufWriteReg;
		int[] bufWriteData;
		try {

			bufWriteReg = hexStringToBytes("03");
			bufWriteData = hexStringToBytes(setGao);
			commandPublic(bufWriteReg, bufWriteData);
			Thread.sleep(30);
			bufWriteReg = hexStringToBytes("04");
			bufWriteData = hexStringToBytes(setDi);
			commandPublic(bufWriteReg, bufWriteData);
			Thread.sleep(30);
			bufWriteReg = hexStringToBytes("b1");
			bufWriteData = hexStringToBytes("b0");
			commandPublic(bufWriteReg, bufWriteData);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	// 爆光度
	public void baoguang(String solarize) {
		int[] bufWriteReg;
		int[] bufWriteData;
		bufWriteReg = hexStringToBytes("b0");
		bufWriteData = hexStringToBytes(solarize);
		commandPublic(bufWriteReg, bufWriteData);
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		if (event.sensor.getType() == Sensor.TYPE_LIGHT) {

			float[] values = event.values;
			if (values[0] < 800) {
				isopenThatLight = 0;
				photosensitive(50, 0, 35);
			} else if (values[0] <= 3000) {
				isopenThatLight = 0;
				photosensitive(50, 0, 35);
			} else if (values[0] <= 6000) {
				isopenThatLight = 0;
				photosensitive(50, 0, 35);
			} else if (values[0] <= 20000) {
				isopenThatLight = 0;
				photosensitive(50, 0, 45);
			} else if (values[0] <= 60000) {
				isopenThatLight = 0;
				photosensitive(50, 0, 50);
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	/**
	 * Convert char to byte
	 * 
	 * @param char
	 * @return byte
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	/**
	 * Convert hex string to byte[]
	 * 
	 * @param hexString
	 *            the hex string
	 * @return byte[]
	 */
	public static int[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		int[] d = new int[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (int) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	/*
	 * 打开闪光灯
	 */
	public static void turnLightOn(Camera mCamera) {
		if (mCamera == null) {
			return;
		}
		Parameters parameters = mCamera.getParameters();
		if (parameters == null) {
			return;
		}
		List<String> flashModes = parameters.getSupportedFlashModes();
		// Check if camera flash exists
		if (flashModes == null) {
			// Use the screen as a flashlight (next best thing)
			return;
		}
		String flashMode = parameters.getFlashMode();
		if (!Parameters.FLASH_MODE_TORCH.equals(flashMode)) {
			// Turn on the flash
			if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
				parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
				mCamera.setParameters(parameters);
			} else {
				
			}
		}
	}

	/*
	 * 关闭闪光灯
	 */
	public static void turnLightOff(Camera mCamera) {
		if (mCamera == null) {
			return;
		}
		Parameters parameters = mCamera.getParameters();
		if (parameters == null) {
			return;
		}
		List<String> flashModes = parameters.getSupportedFlashModes();
		String flashMode = parameters.getFlashMode();
		// Check if camera flash exists
		if (flashModes == null) {
			return;
		}
		if (!Parameters.FLASH_MODE_OFF.equals(flashMode)) {
			// Turn off the flash
			if (flashModes.contains(Parameters.FLASH_MODE_OFF)) {
				parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
				mCamera.setParameters(parameters);
			} else {
				Log.e(TAG, "FLASH_MODE_OFF not supported");
			}
		}
	}
}
